package org.mags.gps.testing;


import org.apache.http.client.fluent.Form;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;

import org.junit.Assert;

public class HTTPAccess extends RemoteAccess {
	public Request getGetMethod(String service) {
		if(!service.startsWith("/"))
			service = "/" + service;
		Request request = Request.Get("http://"+getServer()+":"+getPort()+"/"+getAppName()+"/"+service);
		return request;
	}
	public Request getPostMethod(String service) {
		if(!service.startsWith("/"))
			service = "/" + service;
		Request request = Request.Post("http://"+getServer()+":"+getPort()+"/"+getAppName()+"/"+service);
		return request;
	}
	public void connect() {
		try {
			Form form = Form.form().add("j_username", getUserName()).add("j_password", getPassword()); 
			Response response = getPostMethod("/service/login")
			.bodyForm(form.build())
			.execute();
			String result = response.returnResponse().getStatusLine().toString();
			Assert.assertEquals("HTTP/1.1 200 OK", result);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	public Response executeGet(String service, Form form) {
		Response response;
		try {
			Request request = getGetMethod(service);
			if(form!=null)
				request = request.bodyForm(form.build());
			response = request.execute();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return response;
	}
	public Response executePost(String service, Form form) {
		Response response;
		try {
			Request request = getPostMethod(service);
			if(form!=null)
				request = request.bodyForm(form.build());
			response = request.execute();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return response;
	}
	public void disconnect() {
		try {
			Response response = getPostMethod("/service/logout").execute();
			String result = response.returnResponse().getStatusLine().toString();
			Assert.assertEquals("HTTP/1.1 200 OK", result);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
